package com.david.nfc

import android.annotation.SuppressLint
import android.app.Activity
import android.app.PendingIntent
import android.content.Intent
import android.nfc.FormatException
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.os.Build
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import com.david.nfc.result.NfcParserUtil
import java.io.IOException

/**
 * 添加权限：
 * <uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
 * manifest注册activity时添加action：
 * <intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<meta-data
android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/nfc_tech_filter" />
 *
 * 无界面时不设置contentView即可
 *
 */
class NfcActivity:Activity() {
    private lateinit var tvNFCContent: TextView
    private lateinit var message: TextView
    private lateinit var btnWrite: Button
    private var pendingIntent: PendingIntent? = null

    @SuppressLint("SetTextI18n")
    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)


        NfcUtils.init(applicationContext)
        if (NfcUtils.nfcAdapter == null) {
            // Stop here, we definitely need NFC
            Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show()
            finish()
        }

        val content = NfcUtils.readFromIntent(intent)
        //For when the activity is launched by the intent-filter for android.nfc.action.NDEF_DISCOVERE

        pendingIntent = PendingIntent.getActivity(this, 0,
            Intent(this, javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
            0
        )

        if (!NfcUtils.hasNfc(applicationContext)) {
            Toast.makeText(this, "nfc 不支持或未开启", Toast.LENGTH_LONG).show()
        }

        if(content.isEmpty() || !parseResult(content)){
            setContentView(R.layout.activity_nfc)

            tvNFCContent = findViewById(R.id.nfc_contents)
            message = findViewById(R.id.edit_message)
            btnWrite = findViewById(R.id.button)

            btnWrite.setOnClickListener {
                try {
                    if (NfcUtils.myTag == null) {
                        Toast.makeText(this, NfcUtils.ERROR_DETECTED, Toast.LENGTH_LONG).show()
                    } else {
                        NfcUtils.write(message.text.toString(), NfcUtils.myTag)
                        Toast.makeText(this, NfcUtils.WRITE_SUCCESS, Toast.LENGTH_LONG).show()
                    }
                } catch (e: IOException) {
                    Toast.makeText(this, NfcUtils.WRITE_ERROR, Toast.LENGTH_LONG).show()
                    e.printStackTrace()
                } catch (e: FormatException) {
                    Toast.makeText(this, NfcUtils.WRITE_ERROR, Toast.LENGTH_LONG).show()
                    e.printStackTrace()
                }
            }

            tvNFCContent.text = "Message read from NFC Tag:\n $content"
        } else {
            finish()//读取到且处理了后关闭页面(未打开应用处理时防止activity闪一下)
        }
    }

    /**
     * For reading the NFC when the app is already launched
     */
    @SuppressLint("SetTextI18n")
    override fun onNewIntent(intent: Intent) {
        setIntent(intent)
        val content = NfcUtils.readFromIntent(intent)
        tvNFCContent.text = "Message read from NFC Tag:\n $content"
        if (NfcAdapter.ACTION_TAG_DISCOVERED == intent.action) {
            if (Build.VERSION.SDK_INT >= 33) {
                NfcUtils.myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG, Tag::class.java)
            } else {
                NfcUtils.myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG)
            }
        }

        parseResult(content)
    }

    private fun parseResult(content: String): Boolean{
        return NfcParserUtil.parseResult(this, content)
    }

    public override fun onPause() {
        super.onPause()
        NfcUtils.writeModeOff(this)
    }

    public override fun onResume() {
        super.onResume()
        pendingIntent?.let { NfcUtils.writeModeOn(this, it) }
    }

    override fun onDestroy() {
        super.onDestroy()
        NfcUtils.release()
    }
}